package com.neusoft.nep.supervise.controller;

import com.neusoft.nep.common.Dialog;
import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.common.ViewSwitcher;
import com.neusoft.nep.common.SessionManager;
import com.neusoft.nep.supervise.entity.User;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class UserLoginViewController {
    @FXML
    private Button btn_login;
    @FXML
    private Button btn_register;
    @FXML
    private TextField txt_phoneNumber;
    @FXML
    private PasswordField txt_password;

    public void login() throws IOException {
        Map<String, User> userMap = FileUtils.readMapObject("user.txt");

        String phoneNumber = txt_phoneNumber.getText();
        String password = txt_password.getText();

        if (userMap.containsKey(phoneNumber)) {
            User u = userMap.get(phoneNumber);
            if (password.equals(u.getPassword())) {
                SessionManager.setCurrentUserId(phoneNumber);
                SessionManager.setCurrentUser(u);

                ViewSwitcher.switchView(btn_login, "../supervise/view/MainView.fxml");
            } else {
                Dialog.showDialog("用户登录", "用户密码不正确");
            }
        } else {
            Dialog.showDialog("用户登录", "用户不存在");
        }
    }

    public void register() throws IOException {
        ViewSwitcher.switchView(btn_register, "../supervise/view/UserRegisterView.fxml");
    }
}
